#!/usr/bin/perl
# 2015/01/30 HindIIIから30bp以内のものだけを除く
# 2014/11/12 500bp以上と30-500の２つのファイルを出力するように修正
# 2014/03/13 changed for HiC
# 2012/11/27 Filtering reads pairs by distance from HindIII sites

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;


if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [output filtered map file]\n";
}

#---------------------------------------
# map format
#---------------------------------------
# id chr1 loc1 direction1 quality1 hind1 hind_loc1 chr2 loc2 direction2 quality2 hind2 hind_loc2 type(unique or repeat) number(alignable locations) locations

my %opt;
getopts("i:o:", \%opt);
my $FILE_map = $opt{i};
my $FILE_out = $opt{o};

my $COUNTER_passed = 0;
my $COUNTER_all = 0;


my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/;

	if($hinID1 eq 'NA' or $hinID2 eq 'NA'){
		next;
	}

	$COUNTER_all++;

	my ($dis1, $dis2) = (0,0);
	if($chr1 ne 'NA' and $hinID1 ne 'NA'){
		$dis1 += abs($loc1 - $hinLoc1);
	}

	if($chr2 ne 'NA' and $hinID2 ne 'NA'){
		$dis2 += abs($loc2 - $hinLoc2);
	}

	my $total_length = $dis1 + $dis2;

	if($dis1 < 30 or $dis2 < 30){
		next;
	}

	$fh_out->print("$_\n");
	$COUNTER_passed++;
}
$fh_map->close();
$fh_out->close();

print "Distance from Hind III filter\n";
printf "passed filtered: %d (%.3f)\n", $COUNTER_passed, $COUNTER_passed / $COUNTER_all * 100;
printf "All readds: %d\n", $COUNTER_all;


